首页 > 其他分享 >Go - Handling HTTP Requests

Go - Handling HTTP Requests

时间:2023-10-16 22:45:49浏览次数:33  
标签:body Handling http URL request headers Go HTTP Requests

Problem: You want to process HTTP requests and send back HTTP responses.


Solution: Use http.Request to extract information on HTTP requests and http.ResponseWriter to send HTTP responses back.

 

The http.Request struct represents an HTTP request message sent from the client. The struct contains important information about the request, as well as several useful methods. Some important parts of Request are:
• URL
• Header
• Body
• Form, PostForm, and MultipartForm

You can also get access to the cookies in the request and the referring URL, and the user agent from methods in Request . 

The URL field is a representation of the URL sent as part of the request line (the first line of the HTTP request). The URL field is a pointer to the url.URL type. 

The URL will look like this:

scheme://[userinfo@]host/path[?query]

The two most commonly used pieces of information from the URL of a request are the path and the query. The path is the path to the resource. The query is the query string, which often has the form of a key - value pair, for example, ?key=value . 

You can also get the HTTP method as well as the hostname. The HTTP method is the method used to make the request, such as GET , POST , PUT , DELETE , and so on. The hostname is the name of the server that the request was sent to. 

Here’s a quick look at this:

func   main ()   { 
      http . HandleFunc ( "/hello/world" ,   hello ) 
      http . ListenAndServe ( ":8000" ,   nil ) 
} 

func   hello ( w   http . ResponseWriter ,   r   * http . Request )   { 
      fmt . Fprintf ( w ,   "Method  :  %s,  Host  :  %s" ,   r . Method ,   r . Host ) 
      fmt . Fprintf ( w ,   "Path  :  %s,  Query  :  %s\n" ,   r . URL . Path ,   r . URL . Query ()) 
}

Run this on the server and open http://localhost:8000/hello/world?name=sausheong . Figure 17 - 2 shows a screenshot of a browser showing the method and host of the request, as well as the path and query of the URL.

As you can see, the Query field is a map of key - value pairs. 

Next are the request headers. The Header field of an http.Request is a map of all the HTTP headers sent with the request. The keys in the map are the header names and the values in the map are slices of strings, so if a header appears multiple times in the request, the values will be appended to the slice:

func   main ()   { 
      http . HandleFunc ( "/headers" ,   headers ) 
      http . ListenAndServe ( ":8000" ,   nil ) 
} 

func   headers ( w   http . ResponseWriter ,   r   * http . Request )   { 
      for   k ,   v   :=   range   r . Header   { 
          fmt . Fprintf ( w ,   "%s:  %s\n" ,   k ,   v ) 
      } 
}

Run this on the server and open http://localhost:8000/headers . Figure 17 - 3 is a screenshot of a browser showing the request headers.

Don’t be overly taken by the headers. These are simply the headers that are sent by the browser. In this case, I’m using Safari, so these are the headers sent by Safari. If you use a different browser, you will see different headers. 

Next is the body of a request. The Body field of an http.Request is an io.ReadCloser that contains the request body. The request body is available only if the request has a body, such as a POST request:

func   main ()   { 
      http . HandleFunc ( "/body" ,   body ) 
      http . ListenAndServe ( ":8000" ,   nil ) 
} 

func   body ( w   http . ResponseWriter ,   r   * http . Request )   { 
      body ,   _   :=   io . ReadAll ( r . Body ) 
      fmt . Fprintf ( w ,   "%s" ,   body ) 
}

Since the Body field is an io.ReadCloser , you can use the io.ReadAll function to read the entire body into a byte slice. To test this, you can use the curl command:

$  curl  - X  POST  - d  "Hello  World"  http://localhost:8000/body

The curl command will send a POST request with the body Hello World to the server. The server will then send back the body of the request. If you run this on the command line, you will see the following:

%  curl  - X  POST  - d  "Hello  World"  http://localhost:8000/body
Hello  World

 

标签:body,Handling,http,URL,request,headers,Go,HTTP,Requests
From: https://www.cnblogs.com/zhangzhihui/p/17768581.html

相关文章

  • CF1548E Gregor and the Two Painters
    Day\(\text{叁拾肆}\)。DS写不动了,标题也取不动了www。类似Day1CF1270HNumberofComponents,每个连通块中选出一个代表的点。令一个连通块内所有点按照\(v_{i,j}=\{a_i+b_j,i,j\}\)排序,对最小的\(v_{i,j}\)计数。于是相当于求多少个格子不能走到另一个(非严格)三位偏序......
  • google三驾马车之一:Bigtable解读(英文版)
    本文重点关注了系统设计相关的内容,paper后半部分的具体应用此处没有过多涉及。从个人笔记修改而来,因此为英文版本。Bigtable:ADistributedStorageSystemforStructuredDataDatamodel:notarelationaldatamodelABigtableisasparse,distributed,persistentmul......
  • Go - Creating a UDP Client
    Problem: YouwanttocreateaUDPclienttosenddatatoaUDPserver.Solution: UsetheDialfunctioninthenetpackagetoconnecttoaUDPserver.ThenusetheWritemethodofthenet.UDPConninterfacetowritedatatotheconnection. CreatingaUDP......
  • java.io.IOException: Could not find resource mapper/ProductCategoryMapper.xml 解
    java.io.IOException:Couldnotfindresourcemapper/ProductCategoryMapper.xml解决方案 一、问题背景通过MyBatisPlus测试达梦数据库过程中,运行测试类的时候,项目报错:“java.io.IOException:Couldnotfindresourcemapper/ProductCategoryMapper.xml”工程的目录......
  • django的使用
    配置python环境以及环境变量安转django在cmd输入pipinstalldjangopipshowdjangoLocation:c:\users\tian\appdata\roaming\python\python38\site-packages为django的位置将C:\Users\tian\AppData\Roaming\Python\Python38\Scripts写到环境变量中,在用户变量中点击pa......
  • mongodb 安装
    macOS12.6.7使用.tgz,安装版本4.4参考:https://www.mongodb.com/docs/v4.4/tutorial/install-mongodb-on-os-x-tarball/.tgz方式需要自己创建mongod.conf,这里放到了/etc参考:https://www.mongodb.com/docs/v4.4/reference/configuration-options/https://www.mongodb.com/docs......
  • Codeforces Round 635 (Div. 2) B. Kana and Dragon Quest game
    你需要击败一只巨龙,他有\(h\)点血量,你可以使用以下两种攻击方式:黑洞:使巨龙的血量变为\(\lfloor\frac{h}{2}\rfloor+10\)。可以使用\(n\)次。雷击:使巨龙的血量变为\(h-10\)。可以使用\(m\)次/当巨龙的血量\(h\leq0\)时,你将他击败了。询问你是否可以将他击......
  • [ARC167D] Good Permutation 题解
    题意对于一个长度为\(N\)的排列\(Q\),定义其为好的,当且仅当对于任意整数\(i\in\left[1,N\right]\),在进行若干次操作\(i\leftarrowQ_i\)后可以得到\(i=1\)。给定一个排列\(P\),定义一次操作为交换两个数。定义\(M\)为可以将\(P\)变为一个好的的排列的最小操......
  • Codeforces Round 637 (Div. 2) - Thanks, Ivan Belonogov! A. Nastya and Rice
    纳斯塔亚掉了\(n\)个谷物,每个谷物的重量范围在\([a-b,a+b]\)。她猜测谷物的总重量范围在\([c-d,c+d]\)。询问她的猜测是否正确。显然,若\([n(a-b),n(a+b)]\)和\([c-d,c+d]\)有交,则她的猜测正确。view#include<bits/stdc++.h>typedeflonglongll;......
  • client-go实战之七:准备一个工程管理后续实战的代码
    欢迎访问我的GitHub这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos本篇概览本文是《client-go实战》系列的第八篇,主要内容是新建一个golang工程,用于管理代码,后面整个系列的代码都会保存在这个工程中工程结构简述此工程打算写一个简单......