一条专访是哪个网站做的,有域名如何做网站,产品宣传视频怎么制作,搜索引擎广告的优缺点下午就不能好好学习一下golang#xff0c;业务一直找个不停#xff0c;自己定的业务规则都能忘得一干二净#xff0c;让你查半天#xff0c;完全是浪费时间。 golang实现访问并读取页面数据 package mainimport (fmtnet/http
)var urls []string{… 下午就不能好好学习一下golang业务一直找个不停自己定的业务规则都能忘得一干二净让你查半天完全是浪费时间。 golang实现访问并读取页面数据 package mainimport (fmtnet/http
)var urls []string{http://www.google.com/,http://golang.org/,http://blog.golang.org/,
}
// 使用http.Head方法如果地址不通自己换一个这些是国外的需要代理或者开加速器才行
func main() {// Execute an HTTP HEAD request for all urls// and returns the HTTP status string or an error string.for _, url : range urls {resp, err : http.Head(url)if err ! nil {fmt.Println(Error:, url, err)}fmt.Println(url, : , resp.Status)}
}golang使用http.get package mainimport (fmtio/ioutillognet/http
)func main() {res, err : http.Get(http://www.google.com)checkError(err)// 有些资料这里是ioutil.ReadAll是因为版本低高版本的可以改为以下的包路劲data, err : io.ReadAll(res.Body)checkError(err)// 这里会把网页的页面读取打印出来fmt.Printf(Got: %q, string(data))
}func checkError(err error) {if err ! nil {log.Fatalf(Get : %v, err)}
}通过 xml 包将这个状态解析成为一个结构 package mainimport (encoding/xmlfmtnet/http
)/*这个结构会保存解析后的返回数据。
他们会形成有层级的 XML可以忽略一些无用的数据*/
type Status struct {Text string
}type User struct {XMLName xml.NameStatus Status
}func main() {// 发起请求查询推特 Goodland 用户的状态// 这个地址调不通了是400自己换一个其他的response, _ : http.Get(http://twitter.com/users/Googland.xml)// 初始化 XML 返回值的结构user : User{xml.Name{, user}, Status{}}// 将 XML 解析为我们的结构// 有些资料直接把response.Body放入到xml.Unmarshal中了由于版本不同高版本的这里是放入的btye数组因此使用json方法转了一下byteRes, errorMsg : json.Marshal(response.Body)if errorMsg nil {xml.Unmarshal(byteRes, user)fmt.Printf(status: %s, user.Status.Text)}
}http包中包含了各式各样的函数方法供我们调用 http.Redirect(w ResponseWriter, r *Request, url string, code int)这个函数会让浏览器重定向到 url可以是基于请求 url 的相对路径同时指定状态码。 http.NotFound(w ResponseWriter, r *Request)这个函数将返回网页没有找到HTTP 404 错误。 http.Error(w ResponseWriter, error string, code int)这个函数返回特定的错误信息和 HTTP 代码。 另一个 http.Request 对象 req 的重要属性req.Method这是一个包含 GET 或 POST 字符串用来描述网页是以何种方式被请求的。 w.header().Set(Content-Type, ../..) 设置头信息比如在网页应用发送 html 字符串的时候在输出之前执行 w.Header().Set(“Content-Type”, “text/html”)注w再这里是指http.ResponseWriter 我是demo package mainimport (ionet/http
)const form htmlbodyform action# methodpost namebarinput typetext namein /input typesubmit valuesubmit//form/body/html
/* handle a simple get request */
func SimpleServer(w http.ResponseWriter, request *http.Request) {io.WriteString(w, h1hello, world/h1)
}func FormServer(w http.ResponseWriter, request *http.Request) {w.Header().Set(Content-Type, text/html)switch request.Method {case GET:/* display the form to the user */io.WriteString(w, form)case POST:/* handle the form data, note that ParseForm mustbe called before we can extract form data *///request.ParseForm();//io.WriteString(w, request.Form[in][0])io.WriteString(w, request.FormValue(in))}
}func main() {http.HandleFunc(/test1, SimpleServer)http.HandleFunc(/test2, FormServer)if err : http.ListenAndServe(:8088, nil); err ! nil {panic(err)}
}