go tempplace note
golang note from blackcardriver
function main
func main(){
http.HandleFunc("/getcookie",setcookie)
err := http.ListenAndServe("127.0.0.1:4400", nil)
if err!=nil{
fmt.Println(err)
return
}
}
function main2
func main2(){
mux := http.NewServeMux()
mux.HandleFunc("/", route.Log(route.Hello)
s := &http.Server{
Addr: ":8080",
Handler:mux,
ReadTimeout:10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())
}
** replace use of 'w.Header().Set(“Acces…”)**
func setHeader(w http.ResponseWriter){
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "content-type")
}
reduese the useage of judge if error is nil
func checkerr(err error, tag string){
if err!=nil{
fmt.Println(tag," error: ",err)
}
}
write string to responseWriter in json format
func writehttp(w http.ResponseWriter, str string){
str2,_ := json.Marshal(str)
w.Write(str2)
}
`*parse Request and show the postbody detail
func show_postdata(r *http.Request){
var postbody map[string]string
body, err := ioutil.ReadAll(r.Body)
json.Unmarshal(body, &postbody)
for key,val := range postbody{
fmt.Println(key," --> ",val)
}
}
use a funtion to write http.SetCookie
func set_cookie(w *http.ResponseWriter){
cookie1 := http.Cookie{
Name:"test",
Value:"testvalue",
Path: "/",
MaxAge: 100,
}
http.SetCookie((*w), &cookie1)
}
use a funtion to read cookie
func getcookie(w http.ResponseWriter , r *http.Request){
setHeader(w)
cookie := r.Cookies()
for _,v:= range cookie {
fmt.Println(v.Name,"->",v.Value)
}
return
}
SQL note
connect to postgres sql
var db *sql.DB
const (
host = "localhost"
port = 5432
user = "postgres"
password = "834295"
dbname = "postgres"
)
func init() {
var err error
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err = sql.Open("postgres", psqlInfo)
err = db.Ping()
if err != nil {
log.fatal(err)
}
}
use url to connecto databse
db, err := sql.Open(“postgres”, “postgres://username:password@localhost/db_name?sslmode=disable”)
query (Scan)
command := "select imgurl, linkurl, title from homepagenews order by id desc limit 5"
rows,err := db.Query(command)
defer rows.Close()
if err!= nil{
do something...
}
index := 0
for rows.Next() {
rows.Scan(&...)
}
Insert,delete,updata
command = "insert into.......$1...$2.."
stmt, err := db.Prepare(command)
if err != nil {
do something...
}
_ ,err := stmt.Exec(a,b)
//func (db *DB) Exec(query string, args ...interface{}) (Result, error)
// type Result interface{ LastInserId(), RowsAffected()}
if err != nil {
do something...
}