Programming/golang2025. 11. 24. 19:04

golang 에서 커밋 해시를 바이너리에 넣는 방법을 찾아보는 중

 

아래 방법은 링커에서 변수에 넣는것 같은데 이것도 쓸만해 보이긴 한데..

go build -ldflags "-X my/package/config.Version=1.0.0"

[링크 : https://www.reddit.com/r/golang/comments/rhpbvo/what_kind_of_things_have_you_ran_with_gogenerate/?tl=ko]

 

go version은 좀더 상세한 자료가 들어가는것 같은데 좀더 나은 접근 방법이 될 듯?

go version
The go command now embeds version control information in binaries. It includes the currently checked-out revision, commit time, and a flag indicating whether edited or untracked files are present. Version control information is embedded if the go command is invoked in a directory within a Git, Mercurial, Fossil, or Bazaar repository, and the main package and its containing main module are in the same repository. This information may be omitted using the flag -buildvcs=false.

Additionally, the go command embeds information about the build, including build and tool tags (set with -tags), compiler, assembler, and linker flags (like -gcflags), whether cgo was enabled, and if it was, the values of the cgo environment variables (like CGO_CFLAGS). Both VCS and build information may be read together with module information using go version -m file or runtime/debug.ReadBuildInfo (for the currently running binary) or the new debug/buildinfo package.

The underlying data format of the embedded build information can change with new go releases, so an older version of go may not handle the build information produced with a newer version of go. To read the version information from a binary built with go 1.18, use the go version command and the debug/buildinfo package from go 1.18+.

[링크 : https://tip.golang.org/doc/go1.18#go-command]

'Programming > golang' 카테고리의 다른 글

golang 정적웹 파일 포함하기  (0) 2025.11.24
go vet (golang 정적분석)  (0) 2025.10.02
golang 윈도우 서비스 프로그램 작성하기  (0) 2025.02.18
golang tcp socket timeout 주기(listen, read)  (0) 2024.04.08
golang reflect  (0) 2024.02.20
Posted by 구차니
Programming/golang2025. 11. 24. 18:59

내취향은 아니지만..

go generate 명령을 통해 코드를 생성하고 다시 빌드해서 넣는 듯

 

[링크 : https://go.dev/blog/generate]

[링크 : https://github.com/securego/gosec]

[링크 : https://ccambo.tistory.com/m/entry/Golang-의존성-없이-웹으로-서비스할-정적-파일들을-Golang-바이너리에-추가하기]

'Programming > golang' 카테고리의 다른 글

golang git commit hash  (0) 2025.11.24
go vet (golang 정적분석)  (0) 2025.10.02
golang 윈도우 서비스 프로그램 작성하기  (0) 2025.02.18
golang tcp socket timeout 주기(listen, read)  (0) 2024.04.08
golang reflect  (0) 2024.02.20
Posted by 구차니
Programming/rust2025. 11. 12. 09:24

golang에서는 비트 구조체 안되던것 같은데 러스트에서는 된다고 하니 관심이 증가중 ㅋㅋ

머 리눅스 커널에서도 쓰려고 하는데 설마 없겠어? 싶기도 하네

 

use bit_struct::*; 

enums! {
    // 2 bits, i.e., 0b00, 0b01, 0b10
    pub HouseKind { Urban, Suburban, Rural}
}

bit_struct! {
    // u8 is the base storage type. This can be any multiple of 8
    pub struct HouseConfig(u8) {
        // 2 bits
        kind: HouseKind,
        
        // two's compliment 3-bit signed number
        lowest_floor: i3,
        
        // 2 bit unsigned number
        highest_floor: u2,
    }
}

// We can create a new `HouseConfig` like such:
// where all numbers are statically checked to be in bounds.
let config = HouseConfig::new(HouseKind::Suburban, i3!(-2), u2!(1));

// We can get the raw `u8` which represents `config`:
let raw: u8 = config.raw();
assert_eq!(114_u8, raw);

// or we can get a `HouseConfig` from a `u8` like:
let mut config: HouseConfig = HouseConfig::try_from(114_u8).unwrap();
assert_eq!(config, HouseConfig::new(HouseKind::Suburban, i3!(-2), u2!(1)));
// We need to unwrap because `HouseConfig` is not valid for all numbers. For instance, if the
// most significant bits are `0b11`, it encodes an invalid `HouseKind`. However, 
// if all elements of a struct are always valid (suppose we removed the `kind` field), the struct will
// auto implement a trait which allows calling the non-panicking:
// let config: HouseConfig = HouseConfig::exact_from(123_u8);

// We can access values of `config` like so:
let kind: HouseKind = config.kind().get();

// And we can set values like so:
config.lowest_floor().set(i3!(0));

// We can also convert the new numeric types for alternate bit-widths into the 
// numeric types provided by the standard library:
let lowest_floor: i3 = config.lowest_floor().get();
let lowest_floor_std: i8 = lowest_floor.value();
assert_eq!(lowest_floor_std, 0_i8);

[링크 : https://docs.rs/bit-struct/latest/bit_struct/]

'Programming > rust' 카테고리의 다른 글

rust 참조와 대여  (0) 2025.11.11
rust mut 외 몇가지 컴파일 에러들  (0) 2023.05.26
rust mut  (0) 2023.05.25
rust visibility and privacy  (0) 2023.05.25
rust 소유권  (0) 2023.05.25
Posted by 구차니
Programming/rust2025. 11. 11. 19:29

소유권은 하나만 가지지만, 참조는 소유권이 아니라서 볼수는 있다고

그렇다면.. 공유메모리 처럼 서로 쓰고 지우게 할 수는 없고 무조건 매니저를 거쳐서 하는 구조로 가야하나?

 

[링크 : https://doc.rust-kr.org/ch04-02-references-and-borrowing.html]

'Programming > rust' 카테고리의 다른 글

rust 비트 구조체  (0) 2025.11.12
rust mut 외 몇가지 컴파일 에러들  (0) 2023.05.26
rust mut  (0) 2023.05.25
rust visibility and privacy  (0) 2023.05.25
rust 소유권  (0) 2023.05.25
Posted by 구차니
Programming/C Win32 MFC2025. 10. 11. 18:22

대부분의 경우 소수점 자리만 제한하는데

정수쪽도 길이 제한할일이 있어서 찾아보는데 묘하게 자료가 없어서 테스트 해봄

다만 리눅스에서 한거라 윈도우에서는 다를수 있음

 

void main()
{
	float a = -12.12334;
	printf("%f\n", a);
	printf("%4.1f\n",a);
	printf("%5.1f\n",a);
	printf("%6.1f\n",a);

	printf("%7.1f\n",a);
 	printf("%7.2f\n",a);
	printf("%7.3f\n",a);
   
	printf("%9.1f\n",a);
	printf("%9.2f\n",a);
	printf("%9.3f\n",a);
}

 

$ ./a.out 
-12.123340
-12.1
-12.1
 -12.1
  -12.1
 -12.12
-12.123
    -12.1
   -12.12
  -12.123

 

 

%7.1f / %7.2f / %7.3f 와

%9.1f / %9.2f / %9.3f 가

어떻게 보면 내가 하고 싶었던 결과인데 자리를 정리하면 아래와 같이 나온다.

  1 2 3 4 5 6 7 8 9
%7.3f - 1 2 . 1 2 3    
%9.3f     - 1 2 . 1 2 3

 

정리하자면

%n.mf 에서

n은 정수 부분, 소수점, 부호 를 포함한 전체 길이이고

m은 그중 소수점의 자릿수. m은 n 보다 작아야 한다.

 

'Programming > C Win32 MFC' 카테고리의 다른 글

free(): invalid next size (normal)  (0) 2023.12.18
c에서 cpp 함수 불러오기  (0) 2023.01.04
MSB / LSB 변환  (0) 2022.08.29
kore - c restful api server  (1) 2022.07.07
fopen exclusivly  (0) 2021.07.09
Posted by 구차니

대충~ 3.10 부터 추가되었다는 이야기

 

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something's wrong with the internet"
Note the last block: the “variable name” _ acts as a wildcard and never fails to match. If no case matches, none of the branches is executed.

You can combine several literals in a single pattern using | (“or”):

case 401 | 403 | 404:
    return "Not allowed"

class Point:
    x: int
    y: int

def where_is(point):
    match point:
        case Point(x=0, y=0):
            print("Origin")
        case Point(x=0, y=y):
            print(f"Y={y}")
        case Point(x=x, y=0):
            print(f"X={x}")
        case Point():
            print("Somewhere else")
        case _:
            print("Not a point")

[링크 : https://docs.python.org/ko/3.10/tutorial/controlflow.html#match-statements]

[링크 : https://okeybox.tistory.com/395]

[링크 : https://leapcell.io/blog/ko/python-eseo-switch-muneul-jakseonghaneun-bangbeop-2025-switch-case-yeeje]

[링크 : https://www.bangseongbeom.com/python-switch-case]

 

PEP - Program Enhance Proposal

[링크 : https://wikidocs.net/7896]

 

2020년에 작성되었고, 3.10 버전에 추가됨.

PEP 636 – Structural Pattern Matching: Tutorial
Author: Daniel F Moisset <dfmoisset at gmail.com>
Sponsor: Guido van Rossum <guido at python.org>
BDFL-Delegate:
Discussions-To: Python-Dev list
Status: Final
Type: Informational
Created: 12-Sep-2020
Python-Version: 3.10
Post-History: 22-Oct-2020, 08-Feb-2021
Resolution: Python-Committers message

[링크 : https://peps.python.org/pep-0636/]

 

아니 본인이 2006년에 썼다가 reject 했어?

PEP 3103 – A Switch/Case Statement
Author:Guido van Rossum <guido at python.org>
Status:Rejected
Type:Standards Track
Created:25-Jun-2006
Python-Version:3.0
Post-History:26-Jun-2006

[링크 : https://peps.python.org/pep-3103/]

Posted by 구차니
Programming/golang2025. 10. 2. 10:54

'Programming > golang' 카테고리의 다른 글

golang git commit hash  (0) 2025.11.24
golang 정적웹 파일 포함하기  (0) 2025.11.24
golang 윈도우 서비스 프로그램 작성하기  (0) 2025.02.18
golang tcp socket timeout 주기(listen, read)  (0) 2024.04.08
golang reflect  (0) 2024.02.20
Posted by 구차니

def main() 이 없으니까

독립적으로 실행중인지, import 되어 다른데서 실행을 하는건지 알 필요가 있을때

아래의 문구를 통해서 실행하거나 라이브러리로 작동시키거나 할 수 있다.

if __name__ == "__main__":
    print("run!")

 

[링크 : https://dev-jy.tistory.com/14]

Posted by 구차니

gpt와 검색을 버무려서~

 

pip로 대~~~충 flask 설치하고

Flask 에 static_url_path와 static_folder 를 설정해서 정적으로 서빙할 경로를 지정한다.

template_folder는 template engine를 위한 경로 같긴한데, 지금은 그걸 하려는게 아니니 패스~ 하고

 

/ 로 요청이 들어오면 index.html을 던지도록 라우터 하나 설정하고

나머지는 자동으로 static 경로 하위에서 제공

그리고 /api 쪽은 별도로 라우터 지정해서 2개의 api를 생성해준다.

 

/app.py

from flask import Flask, jsonify, render_template

app = Flask(__name__,
            static_url_path='', 
            static_folder='static',
            template_folder='templates')

@app.route('/')
def serve_index():
    return app.send_static_file('index.html')

# REST API 라우트
@app.route('/api/hello')
def api_hello():
    return jsonify({"message": "Hello, this is a REST API response!"})

# 또 다른 REST API
@app.route('/api/sum/<int:a>/<int:b>')
def api_sum(a, b):
    return jsonify({"a": a, "b": b, "sum": a + b})


if __name__ == "__main__":
    # 디버그 모드 실행
    app.run(debug=True)

 

/static/index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Flask Static + REST API</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>Hello Flask</h1>
    <p>이 페이지는 Flask가 제공하는 정적 웹입니다.</p>

    <button onclick="callApi()">API 호출</button>
    <p id="result"></p>

    <script>
        async function callApi() {
            const res = await fetch("/api/hello");
            const data = await res.json();
            document.getElementById("result").innerText = data.message;
        }
    </script>
</body>
</html>

 

/static/test.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Flask Static + REST API</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>this is test</h1>
</body>
</html>

 

/static/style.css

body {
    font-family: sans-serif;
    background: #f0f0f0;
    padding: 20px;
}
h1 {
    color: darkblue;
}

 

[링크 : https://stackoverflow.com/questions/20646822/how-to-serve-static-files-in-flask]

 

 

$ python3 app.py
 * Serving Flask app 'app'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 997-788-229

 

웹에서 접속하면 아래처럼 뜨는데

보니 template 엔진을 이용해서 치환하도록 해놨어서 css가 안 읽혔군

127.0.0.1 - - [29/Sep/2025 10:48:26] "GET / HTTP/1.1" 304 -
127.0.0.1 - - [29/Sep/2025 10:48:26] "GET /{{%20url_for('static',%20filename='style.css')%20}} HTTP/1.1" 404 -

 

그럼 template 안쓸꺼니 수정해보자

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Flask Static + REST API</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Hello Flask</h1>
    <p>이 페이지는 Flask가 제공하는 정적 웹입니다.</p>

    <button onclick="callApi()">API 호출</button>
    <p id="result"></p>

    <script>
        async function callApi() {
            const res = await fetch("/api/hello");
            const data = await res.json();
            document.getElementById("result").innerText = data.message;
        }
    </script>
</body>
</html>

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Flask Static + REST API</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>this is test</h1>
</body>
</html>

 

이쁘게 잘나온다. 그런데 처음 접속하면 static web이라도 제법 느린데 캐싱이 안되나?

 

localhost:5000/

localhost:5000/index.html

localhost:5000/test.html

localhost:5000/api/hello

localhost:5000/api/sum/2/3

'Programming > python(파이썬)' 카테고리의 다른 글

python switch-case -> match-case  (0) 2025.10.11
python __name__  (0) 2025.09.29
python simsimd  (0) 2025.08.28
python 원하는 버전 설치 및 연결하기  (0) 2025.08.26
pip 패키지 완전 삭제하기  (0) 2025.08.13
Posted by 구차니
Programming/web 관련2025. 9. 5. 17:42

'Programming > web 관련' 카테고리의 다른 글

restful API  (0) 2025.07.15
html custom tag  (0) 2025.05.14
polypill  (0) 2025.03.05
css 캐로젤  (0) 2024.11.12
webgl + three.js를 이용한 GL 공부하기 (feat 클로드)  (0) 2024.10.18
Posted by 구차니