Goвно / Говнокод #26349 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
// GostServer is the type that contains all of the relevant information to set
// up the GOST HTTP Server
type GostServer struct {
	host       string      // Hostname for example "localhost" or "192.168.1.14"
	port       int         // Port number where you want to run your http server on
	api        *models.API // SensorThings api to interact with from the HttpServer
	https      bool
	httpsCert  string
	httpsKey   string
	httpServer *http.Server
}

// CreateServer initialises a new GOST HTTPServer based on the given parameters
func CreateServer(host string, port int, api *models.API, https bool, httpsCert, httpsKey string) Server {
	setupLogger()
	a := *api
	router := CreateRouter(api)
	return &GostServer{
		host:      host,
		port:      port,
		api:       api,
		https:     https,
		httpsCert: httpsCert,
		httpsKey:  httpsKey,
		httpServer: &http.Server{
			Addr:         fmt.Sprintf("%s:%s", host, strconv.Itoa(port)),
			Handler:      PostProcessHandler(RequestErrorHandler(LowerCaseURI(router)), a.GetConfig().Server.ExternalURI),
			ReadTimeout:  30 * time.Second,
			WriteTimeout: 30 * time.Second,
		},
	}
}

// Start command to start the GOST HTTPServer
func (s *GostServer) Start() {
	t := "HTTP"
	if s.https {
		t = "HTTPS"
	}

	logger.Infof("Started GOST %v Server on %v:%v", t, s.host, s.port)

	var err error
	if s.https {
		err = s.httpServer.ListenAndServeTLS(s.httpsCert, s.httpsKey)
	} else {
		err = s.httpServer.ListenAndServe()
	}

	if err != nil {
		logger.Panicf("GOST server not properly stopped: %v", err)
	}
}

// Stop command to stop the GOST HTTP server
func (s *GostServer) Stop() {
	if s.httpServer != nil {
		logger.Info("Stopping HTTP(S) Server")
		s.httpServer.Shutdown(context.Background())
	}
}

Нашёл ГостСервер го

https://github.com/gost/server/blob/master/http/gostserver.go

Запостил: gostinho gostinho, (Updated )

Комментарии (23) RSS

  • > SensorThings
    - погуглил шо это, сепульки какие-то. "The OGC SensorThings API is an OGC standard specification for providing an open and unified way to interconnect IoT devices, data, and applications over the Web". Ещё и от людей с фамилиями Liang, Huang и Khalafbeigi (это типа half beige, полубежевый?)
    Ответить
  • forwardedURI := r.Header.Get("X-Forwarded-For")
    
    rec := httptest.NewRecorder()
    
    // first run the next handler and get results
    h.ServeHTTP(rec, r)
    
    // read response body and replace links
    bytes := rec.Body.Bytes()
    s := string(bytes)
    if len(s) > 0 {
    	if len(forwardedURI) > 0 {
    		// if both are changed (X-Forwarded-For and External uri environment variabele) use the last one
    		if origURI == "http://localhost:8080/" {
    			s = strings.Replace(s, "localhost", forwardedURI, -1)
    		}
    	}
    
    }
    // handle headers too...
    for k, v := range rec.HeaderMap {
    	val := v[0]
    
    	// if there is a location header and a proxy running, change
    	// the location url too
    	if k == "Location" && len(forwardedURI) > 0 {
    		if origURI == "http://localhost:8080/" {
    			logger.Debugf("proxy + location header detected. forwarded uri: %s", forwardedURI)
    			// idea: run net.LookupAddr(forwardeduri) to get hostname instead of ip address?
    			val = strings.Replace(val, "localhost", forwardedURI, -1)
    		}
    	}
    
    	// add the header to response
    	w.Header().Add(k, val)
    }

    Какое GOвно.
    Ответить
    • Довольно примитивный язычишко, думаю, не сложнее делфей.
      Можно было бы подучить на досуге, если бы не одно НО: нахуя мне знать го??

      Аа, он ещё и объекто-ориентированный... Ванильное говно.
      Ответить
        • Ну как же, классы есть, точнее, уже готовые объекты. Всё, что после точки, например"string.length" - это вызов метода класса. Тот факт, что нельзя запилить свои - отдельная тема.

          type GostServer struct {
          	host       string      // Hostname for example "localhost" or "192.168.1.14"
          	port       int         // Port number where you want to run your http server on
          	api        *models.API // SensorThings api to interact with from the HttpServer
          	https      bool
          	httpsCert  string
          	httpsKey   string
          	httpServer *http.Server // уау, типизированный указатель, совсем как в пасцале сях )


          и внезапно - оператор присваивания ':='
          Ответить
          • Мда. Утром почитал в википездии. Лучше бы не читал. Проблем новый линг создаст несоизмеримо больше, чем его предки по-отдельности.

            Вообще, стоит взять на заметку тем, кто хочет разработать уневерсальный язезыг -
            старые проблемы Вам, быть может, удастся спрятать под ковёр, но всегда появятся новые, к которым кодомартышки ещё не готовы.

            Всегда помните об этом.
            Ответить
            • > Проблем новый линг создаст несоизмеримо больше, чем его предки по-отдельности.

              Любопытства ради: а про какие проблемы речь?
              Ответить
              • Главная проблема — «Аналбою» понадобится время на его изучение, потому что в учебном заведении ему этот язык не преподавали.
                Ответить
    • Хотел написать, что в этом разделе новый код два раза в год. Но оказалось, что сейчас кодов немножко больше. За 2020-й год целых шесть тем!
      Ответить
      • А я же правильно понимаю, что go это замена скриптушни, чтобы ошибки отлавливать статической типизацией и линковаться статически со всем, чтобы не требовать интерпретатора/рантайма?
        Ответить
        • The key point here is our programmers are Googlers, they’re not researchers. They’re typically, fairly young, fresh out of school, probably learned Java, maybe learned C or C++, probably learned Python. They’re not capable of understanding a brilliant language but we want to use them to build good software. So, the language that we give them has to be easy for them to understand and easy to adopt.

          -- Rob Pike, creator of Go

          Это недоязык, сделанный для того, чтобы держать обезьянок заменяемыми.
          Ответить
          • Ну да, верно: в гугле (как любой крупной компании) очень много тупых задач автоматизации всякой петушни, которую могут делать мартышки, не осилившие С++ и пр.

            Двадцать лет назад они бы делали это на перле или питоне, но на го у них получится стабильнее
            Ответить
          • > they're not capable of understanding a brilliant language

            Его никто ещё за такие высказывания не взъебал?

            К слову, а какой язык подразумевается под brilliant language?
            Ответить

Добавить комментарий

Семь раз отмерь — один отрежь, guest!

    А не использовать ли нам bbcode?


    8