Dienstag, 24. November 2009

golang networking

a simple get for http:

package main

import (
"io";
"strings";
"log";
"http";
"fmt";
)

func main() {
r, _, err := http.Get("http://www.google.com/robots.txt");
var b []byte;
if err == nil {
b, err = io.ReadAll(r.Body);
r.Body.Close();
}

if err != nil {
log.Stderr(err)
} else {
fmt.Println(string(b));
}
}

ok, it was not very simple.
r, _, err := http.Get("http://www.google.com/robots.txt");
get the Response in r. Response has: a StatusCode, Body and Header.

type Response struct {
Status string; // e.g. "200 OK"
StatusCode int; // e.g. 200
Header map[string]string;
Body io.ReadCloser;
}

Header is a simple string hash. Body is an interface to ReadCloser: all structures with Read and Close.
func Get(url string) (r *Response, finalURL string, err os.Error) is doing followings:
- do a redirection loop (maximal 10 times)
- parse the url
- send the request
- if should redirect, get the new location in header
- if should not redirect: return the result from send()

b, err = io.ReadAll(r.Body);
read the data from response body (which has a reader from connection) in a byte array.
fmt.Println(string(b));
printout the bytes as string

create a simple webserver

package main

import (
"http";
"io";
)

// hello world, the web server
func HelloServer(c *http.Conn, req *http.Request) {
io.WriteString(c, "hello, world!\n");
}

// call a html page
func MyServerPage(c *http.Conn, req *http.Request) {
http.ServeFile(c, req, "myhtml.html");
}

func main() {
http.Handle("/hello", http.HandlerFunc(HelloServer));
http.Handle("/my.html", http.HandlerFunc(MyServerPage));
err := http.ListenAndServe(":8080", nil);
if err != nil {
panic("ListenAndServe: ", err.String())
}
}

http.Handle("/hello", http.HandlerFunc(HelloServer));
set the hadler function HelloServer with "/hello".

err := http.ListenAndServe(":8080", nil);
start the TCP server on port 8080, that handle the registered handler.

io.WriteString(c, "hello, world!\n"); write a simple string.

http.ServeFile(c, req, "myhtml.html"); read the file and print it out.

2 Kommentare:

  1. Thanks for this code, I was in the process of working out how to do just this!

    By the way, in go, there is no need for any semicolons at the end of each line.

    AntwortenLöschen
  2. ReadAll is now moved to package io.ioutil

    AntwortenLöschen