]> Cypherpunks repositories - gostls13.git/commitdiff
simplify various code using new map index rule
authorRuss Cox <rsc@golang.org>
Tue, 30 Mar 2010 17:51:11 +0000 (10:51 -0700)
committerRuss Cox <rsc@golang.org>
Tue, 30 Mar 2010 17:51:11 +0000 (10:51 -0700)
R=r
CC=golang-dev
https://golang.org/cl/833044

27 files changed:
src/cmd/godoc/index.go
src/cmd/goinstall/main.go
src/cmd/hgpatch/main.go
src/pkg/container/heap/heap_test.go
src/pkg/crypto/tls/ca_set.go
src/pkg/debug/dwarf/type_test.go
src/pkg/exp/eval/expr.go
src/pkg/exp/eval/type.go
src/pkg/exp/eval/value.go
src/pkg/exp/ogle/rtype.go
src/pkg/expvar/expvar.go
src/pkg/flag/flag.go
src/pkg/go/parser/parser_test.go
src/pkg/gob/decoder.go
src/pkg/gob/type.go
src/pkg/http/request.go
src/pkg/http/response.go
src/pkg/http/transfer.go
src/pkg/mime/type.go
src/pkg/net/hosts.go
src/pkg/once/once.go
src/pkg/reflect/deepequal.go
src/pkg/reflect/type.go
src/pkg/websocket/client.go
src/pkg/websocket/server.go
src/pkg/websocket/websocket_test.go
test/bench/k-nucleotide.go

index aa108d0db5ffdeade6eb23636270c1d7dc8240e7..a2c71c97bd1daf591c2645ac2e2c6a00db4a5a82 100644 (file)
@@ -682,8 +682,8 @@ func (x *Index) Size() (nwords int, nspots int) {
 
 
 func (x *Index) LookupWord(w string) (match *LookupResult, alt *AltWords) {
-       match, _ = x.words[w]
-       alt, _ = x.alts[canonical(w)]
+       match = x.words[w]
+       alt = x.alts[canonical(w)]
        // remove current spelling from alternatives
        // (if there is no match, the alternatives do
        // not contain the current spelling)
index bc6301baa2649ed5f6f51d54bb939cdd49b56aaf..59e66288b9d84dc484b65917d3eac96536bd705f 100644 (file)
@@ -85,7 +85,7 @@ func printDeps(pkg string) {
 // install installs the package named by path, which is needed by parent.
 func install(pkg, parent string) {
        // Make sure we're not already trying to install pkg.
-       switch v, _ := visit[pkg]; v {
+       switch visit[pkg] {
        case done:
                return
        case visiting:
index 3d18971cf7bcb462d6fe3ec740693a3c0bd75fa4..89aebda55228079cc3307b45b4d5c4dcba22af95 100644 (file)
@@ -62,20 +62,20 @@ func main() {
        // Make sure we won't be editing files with local pending changes.
        dirtylist, err := hgModified()
        chk(err)
-       dirty := make(map[string]int)
+       dirty := make(map[string]bool)
        for _, f := range dirtylist {
-               dirty[f] = 1
+               dirty[f] = true
        }
-       conflict := make(map[string]int)
+       conflict := make(map[string]bool)
        for _, f := range pset.File {
                if f.Verb == patch.Delete || f.Verb == patch.Rename {
-                       if _, ok := dirty[f.Src]; ok {
-                               conflict[f.Src] = 1
+                       if dirty[f.Src] {
+                               conflict[f.Src] = true
                        }
                }
                if f.Verb != patch.Delete {
-                       if _, ok := dirty[f.Dst]; ok {
-                               conflict[f.Dst] = 1
+                       if dirty[f.Dst] {
+                               conflict[f.Dst] = true
                        }
                }
        }
index 8130555f38d737208094fdfbd8d583bfdf34bfe1..89d444dd54655ca683b126e417cc1591d62ad5ff 100644 (file)
@@ -149,9 +149,9 @@ func TestRemove2(t *testing.T) {
        }
        h.verify(t, 0)
 
-       m := make(map[int]int)
+       m := make(map[int]bool)
        for h.Len() > 0 {
-               m[Remove(h, (h.Len()-1)/2).(int)] = 1
+               m[Remove(h, (h.Len()-1)/2).(int)] = true
                h.verify(t, 0)
        }
 
@@ -159,7 +159,7 @@ func TestRemove2(t *testing.T) {
                t.Errorf("len(m) = %d; want %d", len(m), N)
        }
        for i := 0; i < len(m); i++ {
-               if _, exists := m[i]; !exists {
+               if !m[i] {
                        t.Errorf("m[%d] doesn't exist", i)
                }
        }
index c11539c8b16a62c63214466aa288518ecb0f20ff..7f7566e4609a46ee382dc9234dc448a424eb13e0 100644 (file)
@@ -29,18 +29,10 @@ func nameToKey(name *x509.Name) string {
 // FindParent attempts to find the certificate in s which signs the given
 // certificate. If no such certificate can be found, it returns nil.
 func (s *CASet) FindParent(cert *x509.Certificate) (parent *x509.Certificate) {
-       var ok bool
-
        if len(cert.AuthorityKeyId) > 0 {
-               parent, ok = s.bySubjectKeyId[string(cert.AuthorityKeyId)]
-       } else {
-               parent, ok = s.byName[nameToKey(&cert.Issuer)]
-       }
-
-       if !ok {
-               return nil
+               return s.bySubjectKeyId[string(cert.AuthorityKeyId)]
        }
-       return parent
+       return s.byName[nameToKey(&cert.Issuer)]
 }
 
 // SetFromPEM attempts to parse a series of PEM encoded root certificates. It
index c3e456024c94f2be86da5402e5118b116b36d727..6c2daaa56d6a7a598a4ab7e1b1e63b1ff5c8248d 100644 (file)
@@ -87,7 +87,7 @@ func testTypedefs(t *testing.T, d *Data) {
                        }
 
                        if want, ok := typedefTests[t1.Name]; ok {
-                               if _, ok := seen[t1.Name]; ok {
+                               if seen[t1.Name] {
                                        t.Errorf("multiple definitions for %s", t1.Name)
                                }
                                seen[t1.Name] = true
@@ -102,7 +102,7 @@ func testTypedefs(t *testing.T, d *Data) {
        }
 
        for k := range typedefTests {
-               if _, ok := seen[k]; !ok {
+               if !seen[k] {
                        t.Errorf("missing %s", k)
                }
        }
index e630578bdd01e0c827f51b53401f2377e4aafd86..15520830ffa6f88ac0313150bfe74b24d708a4ef 100644 (file)
@@ -845,7 +845,7 @@ func (a *exprInfo) compileSelectorExpr(v *expr, name string) *expr {
                }
 
                // Don't check the same type twice and avoid loops
-               if _, ok := visited[t]; ok {
+               if visited[t] {
                        return nil
                }
                visited[t] = true
index fbb428679e1edd8d2421172995ff798935ff15b0..8a0a2cf2faa7c54d85a01e1e132d1fd67404ca44 100644 (file)
@@ -119,7 +119,7 @@ nextEnt:
 
 func (m typeArrayMap) Put(key []Type, v interface{}) interface{} {
        hash := hashTypeArray(key)
-       ent, _ := m[hash]
+       ent := m[hash]
 
        new := &typeArrayMapEntry{key, v, ent}
        m[hash] = new
index 1558d11ddb35fc614e2cf57806b52b6135dd418f..153349c437dcb8b723dc006e8ee1c6046dceda75 100644 (file)
@@ -539,10 +539,7 @@ type evalMap map[interface{}]Value
 func (m evalMap) Len(t *Thread) int64 { return int64(len(m)) }
 
 func (m evalMap) Elem(t *Thread, key interface{}) Value {
-       if v, ok := m[key]; ok {
-               return v
-       }
-       return nil
+       return m[key]
 }
 
 func (m evalMap) SetElem(t *Thread, key interface{}, val Value) {
index b20acbad5e2eb38851f9f0be99133932d9b06ee8..ce4fdb6637971eab67607cd87600f8621bde568d 100644 (file)
@@ -38,7 +38,7 @@ func newManualType(t eval.Type, arch Arch) *remoteType {
        }
 
        // Get the type map for this architecture
-       typeMap, _ := manualTypes[arch]
+       typeMap := manualTypes[arch]
        if typeMap == nil {
                typeMap = make(map[eval.Type]*remoteType)
                manualTypes[arch] = typeMap
index bed31db5dcfa8ebf2e685ff7bec6c61a1fa310c5..070ba4ee6a39e722081e0b61e2f91172b7d27dab 100644 (file)
@@ -87,10 +87,7 @@ func (v *Map) Init() *Map {
 func (v *Map) Get(key string) Var {
        v.mu.Lock()
        defer v.mu.Unlock()
-       if av, ok := v.m[key]; ok {
-               return av
-       }
-       return nil
+       return v.m[key]
 }
 
 func (v *Map) Set(key string, av Var) {
@@ -168,10 +165,7 @@ func Publish(name string, v Var) {
 
 // Get retrieves a named exported variable.
 func Get(name string) Var {
-       if v, ok := vars[name]; ok {
-               return v
-       }
-       return nil
+       return vars[name]
 }
 
 // RemoveAll removes all exported variables.
index 0c2589c9e93d3314a6c82f14628e241bce861c36..a0cb4f5cae9d5d4896531f69503d338ba8454ebd 100644 (file)
@@ -239,11 +239,7 @@ func Visit(fn func(*Flag)) {
 
 // Lookup returns the Flag structure of the named flag, returning nil if none exists.
 func Lookup(name string) *Flag {
-       f, ok := flags.formal[name]
-       if !ok {
-               return nil
-       }
-       return f
+       return flags.formal[name]
 }
 
 // Set sets the value of the named flag.  It returns true if the set succeeded; false if
index 9db695bd4e06cef95c20a952a9514f9263e23556..f3b91a930faa5405e0e3dee186163f8233ab3b6d 100644 (file)
@@ -91,8 +91,8 @@ func TestParse4(t *testing.T) {
        if len(pkgs) != 1 {
                t.Errorf("incorrect number of packages: %d", len(pkgs))
        }
-       pkg, found := pkgs["parser"]
-       if pkg == nil || !found {
+       pkg := pkgs["parser"]
+       if pkg == nil {
                t.Errorf(`package "parser" not found`)
                return
        }
index 73f0979ed868ba7cd7bd0a052220487282d6200d..90dc2e34c864000ca2a41112fe698312fd873a59 100644 (file)
@@ -40,7 +40,7 @@ func NewDecoder(r io.Reader) *Decoder {
 
 func (dec *Decoder) recvType(id typeId) {
        // Have we already seen this type?  That's an error
-       if _, alreadySeen := dec.wireType[id]; alreadySeen {
+       if dec.wireType[id] != nil {
                dec.state.err = os.ErrorString("gob: duplicate type received")
                return
        }
@@ -109,8 +109,7 @@ func (dec *Decoder) Decode(e interface{}) os.Error {
 
                // No, it's a value.
                // Make sure the type has been defined already.
-               _, ok := dec.wireType[id]
-               if !ok {
+               if dec.wireType[id] == nil {
                        dec.state.err = errBadType
                        break
                }
index f08f2a04d097c9bb143b97418d266254b45c6edf..2a178af04b013711d7ae23d5e76d118b739152a8 100644 (file)
@@ -133,7 +133,7 @@ func newArrayType(name string, elem gobType, length int) *arrayType {
 }
 
 func (a *arrayType) safeString(seen map[typeId]bool) string {
-       if _, ok := seen[a._id]; ok {
+       if seen[a._id] {
                return a.name
        }
        seen[a._id] = true
@@ -155,7 +155,7 @@ func newSliceType(name string, elem gobType) *sliceType {
 }
 
 func (s *sliceType) safeString(seen map[typeId]bool) string {
-       if _, ok := seen[s._id]; ok {
+       if seen[s._id] {
                return s.name
        }
        seen[s._id] = true
index 33c12c024a8695a03c17a4c70e07de06c3cd84e7..83a335bec07e496a95c0a13d39af116d1ad38459 100644 (file)
@@ -49,13 +49,13 @@ type badStringError struct {
 
 func (e *badStringError) String() string { return fmt.Sprintf("%s %q", e.what, e.str) }
 
-var reqExcludeHeader = map[string]int{
-       "Host":              0,
-       "User-Agent":        0,
-       "Referer":           0,
-       "Content-Length":    0,
-       "Transfer-Encoding": 0,
-       "Trailer":           0,
+var reqExcludeHeader = map[string]bool{
+       "Host":              true,
+       "User-Agent":        true,
+       "Referer":           true,
+       "Content-Length":    true,
+       "Transfer-Encoding": true,
+       "Trailer":           true,
 }
 
 // A Request represents a parsed HTTP request header.
@@ -518,24 +518,19 @@ func ReadRequest(b *bufio.Reader) (req *Request, err os.Error) {
        //      Host: doesntmatter
        // the same.  In the second case, any Host line is ignored.
        req.Host = req.URL.Host
-       if v, present := req.Header["Host"]; present {
-               if req.Host == "" {
-                       req.Host = v
-               }
-               req.Header["Host"] = "", false
+       if req.Host == "" {
+               req.Host = req.Header["Host"]
        }
+       req.Header["Host"] = "", false
 
        fixPragmaCacheControl(req.Header)
 
        // Pull out useful fields as a convenience to clients.
-       if v, present := req.Header["Referer"]; present {
-               req.Referer = v
-               req.Header["Referer"] = "", false
-       }
-       if v, present := req.Header["User-Agent"]; present {
-               req.UserAgent = v
-               req.Header["User-Agent"] = "", false
-       }
+       req.Referer = req.Header["Referer"]
+       req.Header["Referer"] = "", false
+
+       req.UserAgent = req.Header["User-Agent"]
+       req.Header["User-Agent"] = "", false
 
        // TODO: Parse specific header values:
        //      Accept
@@ -572,7 +567,7 @@ func ReadRequest(b *bufio.Reader) (req *Request, err os.Error) {
 }
 
 func ParseQuery(query string) (m map[string][]string, err os.Error) {
-       data := make(map[string]*vector.StringVector)
+       m = make(map[string][]string)
        for _, kv := range strings.Split(query, "&", 0) {
                kvPair := strings.Split(kv, "=", 2)
 
@@ -586,17 +581,9 @@ func ParseQuery(query string) (m map[string][]string, err os.Error) {
                        err = e
                }
 
-               vec, ok := data[key]
-               if !ok {
-                       vec = new(vector.StringVector)
-                       data[key] = vec
-               }
+               vec := vector.StringVector(m[key])
                vec.Push(value)
-       }
-
-       m = make(map[string][]string)
-       for k, vec := range data {
-               m[k] = vec.Data()
+               m[key] = vec
        }
 
        return
@@ -618,7 +605,7 @@ func (r *Request) ParseForm() (err os.Error) {
                        r.Form = make(map[string][]string)
                        return os.ErrorString("missing form body")
                }
-               ct, _ := r.Header["Content-Type"]
+               ct := r.Header["Content-Type"]
                switch strings.Split(ct, ";", 2)[0] {
                case "text/plain", "application/x-www-form-urlencoded", "":
                        var b []byte
@@ -643,7 +630,7 @@ func (r *Request) FormValue(key string) string {
        if r.Form == nil {
                r.ParseForm()
        }
-       if vs, ok := r.Form[key]; ok && len(vs) > 0 {
+       if vs := r.Form[key]; len(vs) > 0 {
                return vs[0]
        }
        return ""
index 3a46375765bfa15a6fd80e0eff92b1748ba4cf8c..6a209c9f88ddeceef21aa7a89c32a7e8ca5f2b06 100644 (file)
@@ -16,10 +16,10 @@ import (
        "strings"
 )
 
-var respExcludeHeader = map[string]int{
-       "Content-Length":    0,
-       "Transfer-Encoding": 0,
-       "Trailer":           0,
+var respExcludeHeader = map[string]bool{
+       "Content-Length":    true,
+       "Transfer-Encoding": true,
+       "Trailer":           true,
 }
 
 // Response represents the response from an HTTP request.
@@ -133,7 +133,7 @@ func ReadResponse(r *bufio.Reader, requestMethod string) (resp *Response, err os
 // like
 //     Cache-Control: no-cache
 func fixPragmaCacheControl(header map[string]string) {
-       if v, present := header["Pragma"]; present && v == "no-cache" {
+       if header["Pragma"] == "no-cache" {
                if _, presentcc := header["Cache-Control"]; !presentcc {
                        header["Cache-Control"] = "no-cache"
                }
@@ -157,8 +157,7 @@ func (r *Response) AddHeader(key, value string) {
 // with a comma delimiter.  If there were no response headers with the given
 // key, GetHeader returns an empty string.  Keys are not case sensitive.
 func (r *Response) GetHeader(key string) (value string) {
-       value, _ = r.Header[CanonicalHeaderKey(key)]
-       return
+       return r.Header[CanonicalHeaderKey(key)]
 }
 
 // ProtoAtLeast returns whether the HTTP protocol used
@@ -228,11 +227,11 @@ func (resp *Response) Write(w io.Writer) os.Error {
        return nil
 }
 
-func writeSortedKeyValue(w io.Writer, kvm map[string]string, exclude map[string]int) os.Error {
+func writeSortedKeyValue(w io.Writer, kvm map[string]string, exclude map[string]bool) os.Error {
        kva := make([]string, len(kvm))
        i := 0
        for k, v := range kvm {
-               if _, exc := exclude[k]; !exc {
+               if !exclude[k] {
                        kva[i] = fmt.Sprint(k + ": " + v + "\r\n")
                        i++
                }
index 017077a995ac323973992fc21982b49628e332b7..26266cbcac8e3535f01eb62541131e4a98431ce0 100644 (file)
@@ -340,11 +340,8 @@ func fixLength(status int, requestMethod string, header map[string]string, te []
        // Logic based on media type. The purpose of the following code is just
        // to detect whether the unsupported "multipart/byteranges" is being
        // used. A proper Content-Type parser is needed in the future.
-       if ct, present := header["Content-Type"]; present {
-               ct = strings.ToLower(ct)
-               if strings.Index(ct, "multipart/byteranges") >= 0 {
-                       return -1, ErrNotSupported
-               }
+       if strings.Index(strings.ToLower(header["Content-Type"]), "multipart/byteranges") >= 0 {
+               return -1, ErrNotSupported
        }
 
        // Body-EOF logic based on other methods (like closing, or chunked coding)
index 6d946b5e6ed35817c650823be54ec90460242efb..3706afc473fc9653595aa00bb1881022cca7ceef 100644 (file)
@@ -78,6 +78,5 @@ func initMime() {
 // When ext has no associated type, TypeByExtension returns "".
 func TypeByExtension(ext string) string {
        once.Do(initMime)
-       typ, _ := mimeTypes[ext]
-       return typ
+       return mimeTypes[ext]
 }
index 266ce3f3700400c9625b6e2bcf54d806912545c3..006352b1783b3d80c56fd9244235425a03324b9d 100644 (file)
@@ -44,8 +44,7 @@ func readHosts() {
                        }
                        for i := 1; i < len(f); i++ {
                                h := f[i]
-                               old, _ := hs[h]
-                               hs[h] = appendHost(old, f[0])
+                               hs[h] = appendHost(hs[h], f[0])
                        }
                }
                // Update the data cache.
index b53cd97bd8b5682e9e805627620987c8bdd83dbf..43949ee19798fa1b72a1ad434e17ac4eb5ebfcd6 100644 (file)
@@ -38,8 +38,8 @@ var joblock sync.Mutex
 // func each time f runs, and each of those funcs is run once.
 func Do(f func()) {
        joblock.Lock()
-       j, present := jobs[f]
-       if !present {
+       j := jobs[f]
+       if j == nil {
                // run it
                j = new(job)
                j.Lock()
index 575946c1e13d4a49c6e69ab66dbb14c09e42d53f..a50925e51e68151bafb3f13e63a446c7f6118873 100644 (file)
@@ -45,7 +45,7 @@ func deepValueEqual(v1, v2 Value, visited map[uintptr]*visit, depth int) bool {
 
        // ... or already seen
        h := 17*addr1 + addr2
-       seen, _ := visited[h]
+       seen := visited[h]
        typ := v1.Type()
        for p := seen; p != nil; p = p.next {
                if p.a1 == addr1 && p.a2 == addr2 && p.typ == typ {
index b82f1e23ed6099ef366627923a668f2409b6af64..a8df033af4983a6afe764d43db573d7938572022 100644 (file)
@@ -510,7 +510,7 @@ const inf = 1 << 30 // infinity - no struct has that many nesting levels
 func (t *StructType) fieldByName(name string, mark map[*StructType]bool, depth int) (ff StructField, fd int) {
        fd = inf // field depth
 
-       if _, marked := mark[t]; marked {
+       if mark[t] {
                // Struct already seen.
                return
        }
index 52870800cc4e696dad3e76fff6c4b133d8d48b01..90597a8212559de7fc399c89454f685890cfc33d 100644 (file)
@@ -25,14 +25,10 @@ type ProtocolError struct {
 
 var (
        ErrBadStatus            = &ProtocolError{"bad status"}
-       ErrNoUpgrade            = &ProtocolError{"no upgrade"}
-       ErrBadUpgrade           = &ProtocolError{"bad upgrade"}
-       ErrNoWebSocketOrigin    = &ProtocolError{"no WebSocket-Origin"}
-       ErrBadWebSocketOrigin   = &ProtocolError{"bad WebSocket-Origin"}
-       ErrNoWebSocketLocation  = &ProtocolError{"no WebSocket-Location"}
-       ErrBadWebSocketLocation = &ProtocolError{"bad WebSocket-Location"}
-       ErrNoWebSocketProtocol  = &ProtocolError{"no WebSocket-Protocol"}
-       ErrBadWebSocketProtocol = &ProtocolError{"bad WebSocket-Protocol"}
+       ErrBadUpgrade           = &ProtocolError{"missing or bad upgrade"}
+       ErrBadWebSocketOrigin   = &ProtocolError{"missing or bad WebSocket-Origin"}
+       ErrBadWebSocketLocation = &ProtocolError{"missing or bad WebSocket-Location"}
+       ErrBadWebSocketProtocol = &ProtocolError{"missing or bad WebSocket-Protocol"}
        ErrChallengeResponse    = &ProtocolError{"mismatch challange/response"}
        secKeyRandomChars       [0x30 - 0x21 + 0x7F - 0x3A]byte
 )
@@ -244,40 +240,21 @@ func handshake(resourceName, host, origin, location, protocol string, br *bufio.
        }
 
        // Step 41. check websocket headers.
-       upgrade, found := resp.Header["Upgrade"]
-       if !found {
-               return ErrNoUpgrade
-       }
-       if upgrade != "WebSocket" {
-               return ErrBadUpgrade
-       }
-       connection, found := resp.Header["Connection"]
-       if !found || strings.ToLower(connection) != "upgrade" {
+       if resp.Header["Upgrade"] != "WebSocket" ||
+               strings.ToLower(resp.Header["Connection"]) != "upgrade" {
                return ErrBadUpgrade
        }
 
-       s, found := resp.Header["Sec-Websocket-Origin"]
-       if !found {
-               return ErrNoWebSocketOrigin
-       }
-       if s != origin {
+       if resp.Header["Sec-Websocket-Origin"] != origin {
                return ErrBadWebSocketOrigin
        }
-       s, found = resp.Header["Sec-Websocket-Location"]
-       if !found {
-               return ErrNoWebSocketLocation
-       }
-       if s != location {
+
+       if resp.Header["Sec-Websocket-Location"] != location {
                return ErrBadWebSocketLocation
        }
-       if protocol != "" {
-               s, found = resp.Header["Sec-Websocket-Protocol"]
-               if !found {
-                       return ErrNoWebSocketProtocol
-               }
-               if s != protocol {
-                       return ErrBadWebSocketProtocol
-               }
+
+       if protocol != "" && resp.Header["Sec-Websocket-Protocol"] != protocol {
+               return ErrBadWebSocketProtocol
        }
 
        // Step 42-43. get expected data from challange data.
@@ -322,40 +299,18 @@ func draft75handshake(resourceName, host, origin, location, protocol string, br
        if resp.Status != "101 Web Socket Protocol Handshake" {
                return ErrBadStatus
        }
-       upgrade, found := resp.Header["Upgrade"]
-       if !found {
-               return ErrNoUpgrade
-       }
-       if upgrade != "WebSocket" {
-               return ErrBadUpgrade
-       }
-       connection, found := resp.Header["Connection"]
-       if !found || connection != "Upgrade" {
+       if resp.Header["Upgrade"] != "WebSocket" ||
+               resp.Header["Connection"] != "Upgrade" {
                return ErrBadUpgrade
        }
-
-       ws_origin, found := resp.Header["Websocket-Origin"]
-       if !found {
-               return ErrNoWebSocketOrigin
-       }
-       if ws_origin != origin {
+       if resp.Header["Websocket-Origin"] != origin {
                return ErrBadWebSocketOrigin
        }
-       ws_location, found := resp.Header["Websocket-Location"]
-       if !found {
-               return ErrNoWebSocketLocation
-       }
-       if ws_location != location {
+       if resp.Header["Websocket-Location"] != location {
                return ErrBadWebSocketLocation
        }
-       if protocol != "" {
-               ws_protocol, found := resp.Header["Websocket-Protocol"]
-               if !found {
-                       return ErrNoWebSocketProtocol
-               }
-               if ws_protocol != protocol {
-                       return ErrBadWebSocketProtocol
-               }
+       if protocol != "" && resp.Header["Websocket-Protocol"] != protocol {
+               return ErrBadWebSocketProtocol
        }
        return
 }
index cc1ff938549deda36127ec102dc793c73a0bada5..7faf6ba49e325eeae08dac5f9055dd77f82e5e5e 100644 (file)
@@ -75,14 +75,11 @@ func (f Handler) ServeHTTP(c *http.Conn, req *http.Request) {
        }
        // HTTP version can be safely ignored.
 
-       if v, found := req.Header["Upgrade"]; !found ||
-               strings.ToLower(v) != "websocket" {
-               return
-       }
-       if v, found := req.Header["Connection"]; !found ||
-               strings.ToLower(v) != "upgrade" {
+       if strings.ToLower(req.Header["Upgrade"]) != "websocket" ||
+               strings.ToLower(req.Header["Connection"]) != "upgrade" {
                return
        }
+
        // TODO(ukai): check Host
        origin, found := req.Header["Origin"]
        if !found {
@@ -181,12 +178,12 @@ func (f Draft75Handler) ServeHTTP(c *http.Conn, req *http.Request) {
                io.WriteString(c, "Unexpected request")
                return
        }
-       if v, found := req.Header["Upgrade"]; !found || v != "WebSocket" {
+       if req.Header["Upgrade"] != "WebSocket" {
                c.WriteHeader(http.StatusBadRequest)
                io.WriteString(c, "missing Upgrade: WebSocket header")
                return
        }
-       if v, found := req.Header["Connection"]; !found || v != "Upgrade" {
+       if req.Header["Connection"] != "Upgrade" {
                c.WriteHeader(http.StatusBadRequest)
                io.WriteString(c, "missing Connection: Upgrade header")
                return
index 58065580e7c1e548c0887e81c4b356582cc25260..0762fca699136dad6db73a66b4505e0d928eae80 100644 (file)
@@ -42,18 +42,18 @@ func TestEcho(t *testing.T) {
        ws, err := newClient("/echo", "localhost", "http://localhost",
                "ws://localhost/echo", "", client, handshake)
        if err != nil {
-               t.Errorf("WebSocket handshake error", err)
+               t.Errorf("WebSocket handshake error: %v", err)
                return
        }
 
        msg := []byte("hello, world\n")
        if _, err := ws.Write(msg); err != nil {
-               t.Errorf("Write: error %v", err)
+               t.Errorf("Write: %v", err)
        }
        var actual_msg = make([]byte, 512)
        n, err := ws.Read(actual_msg)
        if err != nil {
-               t.Errorf("Read: error %v", err)
+               t.Errorf("Read: %v", err)
        }
        actual_msg = actual_msg[0:n]
        if !bytes.Equal(msg, actual_msg) {
@@ -73,7 +73,7 @@ func TestEchoDraft75(t *testing.T) {
        ws, err := newClient("/echoDraft75", "localhost", "http://localhost",
                "ws://localhost/echoDraft75", "", client, draft75handshake)
        if err != nil {
-               t.Errorf("WebSocket handshake error", err)
+               t.Errorf("WebSocket handshake: %v", err)
                return
        }
 
@@ -104,7 +104,7 @@ func TestWithQuery(t *testing.T) {
        ws, err := newClient("/echo?q=v", "localhost", "http://localhost",
                "ws://localhost/echo?q=v", "", client, handshake)
        if err != nil {
-               t.Errorf("WebSocket handshake error", err)
+               t.Errorf("WebSocket handshake: %v", err)
                return
        }
        ws.Close()
index b4d4098d0d39098bb2eae95be0aefaf3e97021bf..fdc98ed472505be7bba50fb60eaf50627fa1c94e 100644 (file)
@@ -51,24 +51,15 @@ func count(data string, n int) map[string]int {
        top := len(data) - n
        for i := 0; i <= top; i++ {
                s := data[i : i+n]
-               if k, ok := counts[s]; ok {
-                       counts[s] = k + 1
-               } else {
-                       counts[s] = 1
-               }
+               counts[s]++
        }
        return counts
 }
 
 func countOne(data string, s string) int {
-       counts := count(data, len(s))
-       if i, ok := counts[s]; ok {
-               return i
-       }
-       return 0
+       return count(data, len(s))[s]
 }
 
-
 type kNuc struct {
        name  string
        count int