Summary of code snippets commonly used in Golang development
- 2020-06-03 06:54:19
- OfStack
This article mainly summarizes the code fragments that I used in writing golang application, and provides them for future use, as well as reference and learning for those who need them. Let's have a look at the details.
1. Send user:passwd messages via http package
Send something like curl -u The request of
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 converts unknown objects to 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
}
3. Mux gets the Get Query parameter
vals := r.URL.Query()
oriDriver, ok := vals["driver"]
4. 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)))
Recursively find the file
func readAPK(path string, apk map[string]int) {
// fmt.Println(" To deal with ", 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 failure [%s]\n", file.Name(), err.Error())
return
}
err = json.Unmarshal(body, &ap)
if err != nil {
fmt.Printf("[%s] Parse failure [%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]++
}
}
}
}
}
}
}
}
}
}
6. Parse the existing data of Mongo
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"`
}
Key points:
1. Use the bson modifier
2. Each flag is divided directly by space
3._id and omitempty are used and divided. There can be no whitespace
7. The 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(" The next collection time is [%s]\n", next.Format("200601021504"))
select {
case <-t.C:
err := sync.Gather()
if err != nil {
log.Println(err)
}
}
}
conclusion