Golang frequently used code snippets

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Here is a snippet of code that I used to write the Golang app for later use.

Send user:passwd information via HTTP package

    发送类似于 curl -u 的请求    client := &http.Client{}    req, err := http.NewRequest("GET", <url>, nil)    req.SetBasicAuth(<username>, <userpasswd>)    if err != nil {        log.Fatal(err)    }    resp, err := client.Do(req)    if err != nil {        log.Fatal(err)    }    content, err := ioutil.ReadAll(resp.Body)    if err != nil {        log.Fatal(err)    }

Golang converting an unknown object to an array by reflection

func interfaceSlice(slice interface{}) []interface{} {      s := reflect.ValueOf(slice)    if s.Kind() != reflect.Slice {        panic("InterfaceSlice() given a non-slice type")    }    ret := make([]interface{}, s.Len())    for i := 0; i < s.Len(); i++ {        ret[i] = s.Index(i).Interface()    }    return ret}

Mux Get get query parameter

    vals := r.URL.Query()    oriDriver, ok := vals["driver"]

Mux cross-domain access code

     methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})    headersOk := handlers.AllowedHeaders([]string{"X-Requested-With"})    originsOk := handlers.AllowedOrigins([]string{"*"})    log.Println(http.ListenAndServe(":8000", handlers.CORS(headersOk, originsOk, methodsOk)(r)))

Finding files recursively

    Func readapk (Path string, apk map[string]int) {//FMT. PRINTLN ("Processing", path) files, _: = Ioutil. ReadDir (Path) for _, File: = Range Files {//FMT. Println (file. Name (), file. Isdir ()) if file. Isdir () {readapk (path+ "/" +file. Name (), apk)} else {if Strings.compare (file. Name (), "APK.log") = = 0 {ap: = make (map[string]string) body, err: = Ioutil. ReadFile (path + "/" + file.) Name ()) if err! = Nil {fmt. Printf ("[%s] read failed [%s]\n", file. Name (), Err. Error ()) return} err = json. Unmarshal (body, &AMP;AP) if err! = Nil {fmt. Printf ("[%s] parse failed [%s]\n", file. Name (), Err. Error ()) return} for a: = Range ap {at: = strings.                    Split (Ap[a], "|+|") For _, Atemp: = range at {info: = strings. Split (atemp, "|-|"If Len (info) > 1 {header: = strings. Split (info[1], "") for _, H: = Range Header {if strings. Contains (H, "Referer:") {u, err: = URL. Parserequesturi (h[8:]) if err! = Nil {fmt. Println (Err.                                    Error ())} else {apk[u.host]++                    }                                }                            }                        } }                }            }        }    }}

Parsing data that MONGO already exists

type App struct {      Id string `json:"id" bson:"_id,omitempty"`    User_id string `bson:"user_id"`    Name string `bson:"name"`    Domain string `bson:"domain"`    Business_line string `bson:"business_line"`}重点: 1.使用bson修饰符  2.各个flag直接使用空格分割  3._id和omitempty使用,分割。同时不能存在空格  

Timer

    for {        now := time.Now()        next := now.Add(time.Minute * 10)        next = time.Date(next.Year(), next.Month(), next.Day(), next.Hour(), next.Minute(), 0, 0, next.Location())        t := time.NewTimer(next.Sub(now))        log.Printf("下次采集时间为[%s]\n", next.Format("200601021504"))        select {        case <-t.C:            err := sync.Gather()            if err != nil {                log.Println(err)            }        }    }
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.