Ir notas de estudio de idiomas 12 - biblioteca estándar http

Ir notas de estudio de idiomas 12 - biblioteca estándar http

  • enviar solicitud usando cliente http
  • Use http.Client para controlar los encabezados de solicitud
  • Simplifica tu trabajo con httputil

Código de muestra

package main

import (
	"fmt"
	"net/http"
	"net/http/httputil"
)

func main() {
    
    
	request, err := http.NewRequest(
		http.MethodGet,
		"http://www.imooc.com",
		nil,
	)
	client := http.Client{
    
    
		CheckRedirect: func(
			req *http.Request,
			via []*http.Request) error {
    
    
			fmt.Println("Redirect:", req)
			return nil
		},
	}
	request.Header.Add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1")
	resp, err := client.Do(request)
	if err != nil {
    
    
		panic(err)
	}
	defer resp.Body.Close()
	s, err := httputil.DumpResponse(resp, true)
	if err != nil {
    
    
		panic(err)
	}
	fmt.Printf("%s\n", s)
}

Análisis de rendimiento del servidor http

  • Importar _ "net/http/pprof"
    está subrayado para indicar que, aunque no se usa, es necesario cargar algunos programas auxiliares
  • Visite /debug/pprof/
  • Use go tool pprof para analizar el rendimiento
    , haga clic en el documento de ayuda de net/http/pprof y escriba de acuerdo con el documento

Ver información sobre el servidor
inserte la descripción de la imagen aquí
Ver uso de memoria
inserte la descripción de la imagen aquí

formato de datos JSON

  • La etiqueta de la estructura se utiliza para procesar el nombre del campo.
  • json's marshal y Unmarshal, utilizados para convertir el formato json
  • Tenga en cuenta que no puede cambiar directamente el nombre de la propiedad a minúsculas. En el lenguaje Go, las minúsculas son privadas y no se mostrarán.

Código de muestra

package main

import (
	"encoding/json"
	"fmt"
)

type OrderItem struct {
    
    
	ID    string  `json:"id"`
	Name  string  `json:"name"`
	Price float64 `json:"price"`
}

//不能直接将属性名改为小写,go语言中小写为private不会显示
//可以通过打标签的方式更改json中的属性名
//omitempty当属性为空时不显示,如果不加omitempty会显示一个空字段
type Order struct {
    
    
	ID         string      `json:"id"`
	Items      []OrderItem `json:"items"`
	TotalPrice float64     `json:"total_price"`
}

func main() {
    
    
	unmarshal()
}
func marshal() {
    
    
	o := Order{
    
    
		ID:         "1234",
		TotalPrice: 20,
		Items: []OrderItem{
    
    
			{
    
    
				ID:    "item_1",
				Name:  "learn go",
				Price: 15,
			},
			{
    
    
				ID:    "item_2",
				Name:  "interview",
				Price: 10,
			},
		},
	}
	b, err := json.Marshal(o)
	if err != nil {
    
    
		panic(err)
	}
	fmt.Printf("%s\n", b)
}
func unmarshal() {
    
    
	s := `{"id":"1234","items":[{"id":"item_1","name":"learn go","price":15},{"id":"item_2","name":"interview","price":10}],"total_price":20}`
	var o Order
	err := json.Unmarshal([]byte(s), &o)
	if err != nil {
    
    
		panic(err)
	}
	fmt.Printf("%+v\n", o)
}

marco de ginebra

  • Uso
    de middleware Registre algunas funciones a través de middleware, y todas las solicitudes pasarán por middleware
  • Uso del contexto
    Toda la información sobre la solicitud, usted mismo puede agregar algún valor-clave
package main

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"math/rand"
	"time"
)

func main() {
    
    
	r := gin.Default()
	logger, err := zap.NewProduction()
	if err != nil {
    
    
		panic(err)
	}

	//middleware
	const keyRequestId = "requestId"
	r.Use(func(c *gin.Context) {
    
    
		s := time.Now()
		c.Next()
		// path,status,log latency
		logger.Info("incoming request",
			zap.String("path", c.Request.URL.Path),
			zap.Int("status", c.Writer.Status()),
			zap.Duration("elapsed", time.Now().Sub(s)))
	}, func(c *gin.Context) {
    
    
		//可以在middleware中往context里面塞东西,在具体的handler中拿东西
		c.Set(keyRequestId, rand.Int())
		c.Next()
	})



	//handler 处理对应的路径
	r.GET("/ping", func(c *gin.Context) {
    
    
		h := gin.H{
    
    
			"message": "pong",
		}
		if rid, exists := c.Get(keyRequestId); exists {
    
    
			h[keyRequestId] = rid
		}

		c.JSON(200, h)
	})
	r.GET("/hello", func(c *gin.Context) {
    
    
		c.String(200, "hello")
	})
	r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

Supongo que te gusta

Origin blog.csdn.net/shn111/article/details/122715111
Recomendado
Clasificación